package cn.net.wangyixinwen.mvvm.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;

import cn.net.wangyixinwen.databinding.FragmentHomeBinding;
import cn.net.wangyixinwen.databinding.FragmentJingxuanBinding;
import cn.net.wangyixinwen.mvvm.activity.NewsDetailsActivity;
import cn.net.wangyixinwen.mvvm.adapter.HomeAdapter;
import cn.net.wangyixinwen.mvvm.adapter.JXAdapter;
import cn.net.wangyixinwen.mvvm.vm.HomeVM;
import cn.net.wangyixinwen.mvvm.vm.JXVM;

public class JXFragment extends Fragment {

    private FragmentJingxuanBinding viewBinding;

    private JXVM vm = new JXVM();

    private JXAdapter adapter = new JXAdapter();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        viewBinding = FragmentJingxuanBinding.inflate(LayoutInflater.from(requireContext()));
        return viewBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initObserver();
        GridLayoutManager manager = new GridLayoutManager(requireContext(), 2);
        viewBinding.rvList.setAdapter(adapter);
        viewBinding.rvList.setLayoutManager(manager);

        vm.getData();
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                Intent intent = new Intent(requireContext(), NewsDetailsActivity.class);
                intent.putExtra("data", adapter.getItem(position));
                startActivity(intent);
            }
        });

    }

    public void initObserver() {
        vm.eventList.observe(this, list -> adapter.setNewData(list));
    }

}
